//购物车数组.数组里面的元素是书籍对象和num
let shopList = [];

//加入购物车显示购物车
function buy(bookId) {
  //显示遮罩
  $("shopDiv").style.visibility = "visible";
  $("shopDiv").style.width = document.documentElement.clientWidth+"px";
  $("shopDiv").style.height = document.documentElement.clientHeight+"px";

  //根据商品的id得到购物车对象
  let bookObj = shopList.find(n => n.book.code == bookId);
  if (bookObj == null){//说明在购物车汇总不存在该商品
    //从书籍数组中查询到该商品对象
    bookObj = bookArray.find(n => n.code == bookId);
    //创建购物车对象
    var shopObj = {book:bookObj,num:1};//num默认买一件
    //在购物车中添加元素
    shopList.push(shopObj);
  }
  else {//存在了就直接数量加一
    bookObj.num++;
  }
  showShopInfo();
}

/**
 * 显示购物车信息
 * 价格随数量变化而变化
 */
function showShopInfo() {
  let str = "";
  let sum = 0;
  shopList.forEach(n => {
    str += `<tr><td>${n.book.bookname}</td><td>${n.book.price}</td>
    <td><input type="number" min="1" value="${n.num}" onblur="changeNum(this,${n.book.code})"></td>
    <td>${n.book.price * n.num}</td>
    <td><input type="button" value="移除商品" onclick="del(${n.book.code})"></td></tr>`;
    sum += n.book.price * n.num;
  })
  $("shopData").innerHTML = str;
  $("sumSpan").innerHTML = sum;

}

/**
 * 根据code移除商品
 * @param bookId code
 */
function del(bookId) {

  let index = shopList.findIndex(n => n.book.code == bookId);
  shopList.splice(index,1);
  showShopInfo();
}

/**
 * 修改商品的数量
 * @param txObj 数量文本框的对象
 * @param bookId 购买商品的id
 */
function changeNum(txObj,bookId) {

  if (txObj.value.length == 0 || txObj.value < 1){
    //至少买一件
    txObj.value = 1;
  }

  //根据书籍的编号找到购物车对象
  let shopObj = shopList.find(n => n.book.code == bookId);
  shopObj.num = parseInt(txObj.value);
  showShopInfo();
}


